package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.MessageConstant;
import com.itheima.dao.MenuDao;
import com.itheima.dao.UserDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Menu;
import com.itheima.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service(interfaceClass = MenuService.class)
@Transactional
public class MenuServiceImpl implements MenuService {

    @Autowired
    private MenuDao menuDao;
    @Autowired
    private UserDao userDao;
    //新增菜单项
    public void add(Menu menu) {
        menuDao.add(menu);
    }

    //分页查询
    public PageResult findPage(QueryPageBean queryPageBean) {
        //获取当前页
        Integer currentPage = queryPageBean.getCurrentPage();
        //获取每页记录数
        Integer pageSize = queryPageBean.getPageSize();
        //获取查询条件
        String queryString = queryPageBean.getQueryString();
        //使用分页查询插件开始分页查询
        PageHelper.startPage(currentPage, pageSize);
        Page<Menu> page = menuDao.findPage(queryString);
        List<Menu> rows = page.getResult();//当前页结果
        long total = page.getTotal();//总记录数
        return new PageResult(total, rows);
    }

   //根据id回显数据
    public Menu findById(Integer id) {
        return menuDao.findById(id);
    }

    //编辑
    public void edit(Menu menu) {
        menuDao.edit(menu);
    }

    //根据id删除
   public void delete(Integer id) {
        //判断当前菜单是否已经关联到角色
        long count = menuDao.findCount(id);
        if (count > 0) {
            //已关联,无法删除
            new RuntimeException();
        }
        menuDao.delete(id);
    }


    @Override
    public List<Menu> findMenuByUsername(String username) {
        return userDao.findMenuList(username);

    }


    @Override
    public List<Menu> findAll() {
        return menuDao.findAll();
    }

    @Override
    public List<Menu> findMenuIdsByRoleId(Integer id) {
        return menuDao.findMenuIdsByRoleId(id);
    }
}
